package com.ruoyi.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.domain.vo.CartGoodsDTO;
import com.ruoyi.domain.vo.GoodsEvaluateVo;
import com.ruoyi.domain.vo.GoodsVo;
import com.ruoyi.service.IExchangeMallService;
import com.ruoyi.system.domain.Address;
import com.ruoyi.system.domain.Cart;
import com.ruoyi.system.domain.GoodsEvaluate;
import com.ruoyi.system.domain.vo.GoodsSystemVo;
import com.ruoyi.system.service.ICartService;
import com.ruoyi.system.service.IGoodsService;
import com.ruoyi.system.service.IUserInfoService;
import com.ruoyi.utils.TanpuhuiUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/exchangeMall")
public class ExchangeMallController extends BaseController {

    @Autowired
    IGoodsService goodsServiceImpl;

    @Autowired
    ICartService cartServiceImpl;

    @Autowired
    IUserInfoService userInfoServiceImpl;

    @Autowired
    IExchangeMallService exchangeMallService;

    @Autowired
    com.ruoyi.mapper.CartGoodsDTOMapper cartGoodsDTOMapper;

    @Autowired
    private TanpuhuiUtils tanpuhuiUtils;

    /**
     *  获取用户积分可折扣的金额
     *  @param userId 用户id
     *  @return 积分可折扣的金额
     */
    @GetMapping("/getUserDiscountRMB")
    public AjaxResult getUserDiscountRMB(@RequestParam("userId") Long userId){
         return AjaxResult.success(exchangeMallService.getUserDiscountRMB(userId));
    }

    /**
     *  获取不同类别的商品的热门商品列表
     *  @param goodsTypeId 商品类别id
     *  @param pageNum 页码信息
     *  @param pageSize 页容量信息
     *  @param sortWay 排序方式
     *  @return 商品列表
     */
    @GetMapping("/selectGoodsList")
    public AjaxResult selectGoodsList(@RequestParam("goodsTypeId") Long goodsTypeId, @RequestParam("pageNum") Long pageNum, @RequestParam("pageSize") Long pageSize, @RequestParam("sortWay") String sortWay, @RequestParam("feeShipping") boolean feeShipping){
        List<GoodsSystemVo> goodsList = exchangeMallService.getGoodsList(goodsTypeId, pageNum, pageSize, sortWay, feeShipping);
//        System.out.println(goodsList);
        return AjaxResult.success(goodsList);
    }

    /**
     * 获取热门推荐的商品列表，默认按销量降序
     * @param goodsTypeId 商品类别id
     * @param pageNum 页码信息
     * @param pageSize 页容量信息
     * @param sortWay 排序方式
     * @return 商品列表
     */
    @GetMapping("/selectHotGoodsList")
    public AjaxResult selectHotGoodsList(@RequestParam(value = "goodsTypeId", required = false) Long goodsTypeId, @RequestParam("pageNum") Long pageNum, @RequestParam("pageSize") Long pageSize, @RequestParam(value = "sortWay", required = false) String sortWay, @RequestParam("feeShipping") boolean feeShipping){
        List<GoodsVo> goodsList = exchangeMallService.selectHotGoodsList(goodsTypeId, pageNum, pageSize, sortWay, feeShipping);
        return AjaxResult.success(goodsList);
    }

    /**
     * 获取限时限量的商品列表,默认按剩余时间升序
     * @param goodsTypeId 商品类别id
     * @param pageNum 页码信息
     * @param pageSize 页容量信息
     * @param sortWay 排序方式
     * @return 商品列表
     */
    @GetMapping("/selectTimeGoodsList")
    public AjaxResult selectTimeGoodsList(@RequestParam(value = "goodsTypeId", required = false) Long goodsTypeId, @RequestParam("pageNum") Long pageNum, @RequestParam("pageSize") Long pageSize, @RequestParam(value = "sortWay", required = false) String sortWay, @RequestParam("feeShipping") boolean feeShipping){
        List<GoodsVo> goodsList = exchangeMallService.selectTimeGoodsList(goodsTypeId, pageNum, pageSize, sortWay, feeShipping);
        return AjaxResult.success(goodsList);
    }

    /**
     * 获取用户购物车中的商品列表
     * @param userId 用户id
     * @return 购物车中的商品列表
     */
    @GetMapping("/selectUserCartList")
    public AjaxResult selectUserCartList(@RequestParam("userId") Long userId) {
        List<CartGoodsDTO> cartGoodsList = exchangeMallService.selectUserCartList(userId);
        System.out.println(cartGoodsList);
        // 使用 HashMap 来存储分组后的数据
        Map<String, List<CartGoodsDTO>> groupedCartGoods = new HashMap<>();

        // 遍历 cartGoodsList，将商品按店名分组
        for (CartGoodsDTO item : cartGoodsList) {
//            System.out.println(item);
            if (item.getRelateGoodsId() != null && !Objects.equals(item.getRelateGoodsId(), "")) {
                item.setRelateGoodsList(exchangeMallService.selectRelateGoodsList(item.getRelateGoodsId()));
            }
            String shopName = item.getShopName(); // 假设 CartGoodsDTO 中有 getShopName() 方法

            // 如果Map中不存在该店名，则新建List
            groupedCartGoods.computeIfAbsent(shopName, k -> new ArrayList<>()).add(item);
        }
        AjaxResult ajaxResult = AjaxResult.success(groupedCartGoods);
        ajaxResult.put("goodsTotalCount", cartGoodsList.size()); // 总数
//        System.out.println(groupedCartGoods); // 打印分组后的结果
        return ajaxResult; // 返回分组后的结果
    }

    /**
     * 获取商品的评价信息
     * @param goodsId 商品id
     * @param pageNum  页码信息
     * @param pageSize 页容量信息
     * @return 商品的评价信息
     */
    @GetMapping("/selectGoodsEvaluateListByGoodsId")
    public AjaxResult selectGoodsEvaluateListByGoodsId(@RequestParam("goodsId") Long goodsId, @RequestParam("pageNum") Long pageNum, @RequestParam("pageSize") Long pageSize) {
        List<GoodsEvaluateVo> goodsEvaluateList = exchangeMallService.selectGoodsEvaluateListByGoodsId(goodsId, pageNum, pageSize);
        return AjaxResult.success(goodsEvaluateList);
    }

    /**
     * 获取商品类型的子列表
     * @param goodsTypeId
     */
    @GetMapping("/selectGoodsTypeList")
    public AjaxResult selectGoodsTypeList(@RequestParam("goodsTypeId") Long goodsTypeId) {
        return AjaxResult.success(exchangeMallService.selectGoodsTypeList(goodsTypeId));
    }

    /**
     * 添加购物车,如果商品已存在购物车，则数量增加，否则添加新的商品
     * @param goodsId 商品id
     * @param userId 用户id
     * @param goodsCounts 商品数量
     * @param stander 商品规格
     * @return 结果
     */
    @PostMapping("/addCart")
    public AjaxResult addCart(@RequestParam("goodsId") Long goodsId, @RequestParam("userId") Long userId, @RequestParam(value = "goodsCounts", required = false) Long goodsCounts, @RequestParam(value = "stander", required = false) String stander) {
        if (exchangeMallService.isCartExists(userId, goodsId)){
            exchangeMallService.updateCart(goodsId, userId);
        }
        else {
            exchangeMallService.addCart(goodsId, userId, goodsCounts, stander);
        }
        return AjaxResult.success();
    }

    /**
     * 删除购物车中的商品
     * @param goodsId 商品id
     * @param userId 用户id
     * @return 结果
     */
    @PutMapping("/deleteCart")
    public AjaxResult deleteCart(@RequestParam("goodsId") Long goodsId, @RequestParam("userId") Long userId) {
        if (exchangeMallService.isCartExists(userId, goodsId)){
            System.out.println("购物车存在!");
            exchangeMallService.deleteCart(goodsId, userId);
            return AjaxResult.success();
        }
        else {
            return AjaxResult.error("商品不存在!");
        }
    }

    /**
     * 减少购物车中的商品数量
     * @param goodsId 商品id
     * @param userId 用户id
     * @return 结果
     */
    @PutMapping("/reduceCartCounts")
    public AjaxResult reduceCart(@RequestParam("goodsId") Long goodsId, @RequestParam("userId") Long userId) {
        exchangeMallService.reduceCartCounts(goodsId, userId);
        return AjaxResult.success();
    }

    /**
     * 商品查询
     * @param goodsName 商品名称
     * @return 商品列表
     */
    @GetMapping("/selectGoodsByName")
    public AjaxResult selectGoodsByName(@RequestParam("goodsName") String goodsName, @RequestParam("pageNum") Long pageNum, @RequestParam("pageSize") Long pageSize, @RequestParam("sortWay") String sortWay, @RequestParam("feeShipping") boolean feeShipping) {
        return AjaxResult.success(exchangeMallService.selectGoodsByName(goodsName, pageNum, pageSize, sortWay, feeShipping));
    }

    /**
     * 获取某规格的商品信息
     * @param goodsId 商品id
     * @param stander 商品规格
     * @return 商品信息
     */
    @GetMapping("/selectGoodsByStander")
    public AjaxResult selectGoodsByStander(@RequestParam("goodsId") Long goodsId, @RequestParam("stander") String stander) {
        GoodsVo goods = exchangeMallService.selectGoodsByStander(goodsId, stander);
        return AjaxResult.success(goods);
    }

    /**
     * 新增订单
     * @param userId 用户id
     * @param CartGoodsList 购物车列表
     * @return 结果
     */
    @PostMapping("/createOrder")
    public AjaxResult addOrder(@RequestParam("userId") Long userId, @RequestBody List<CartGoodsDTO> CartGoodsList) {
//        System.out.println(CartGoodsList);
//        System.out.println(userId);
        Long orderId = exchangeMallService.createOrderInfo(userId);
        System.out.println("订单id为"+orderId);
        for (CartGoodsDTO cartGoodsDTO : CartGoodsList) {
            System.out.println(cartGoodsDTO);
            exchangeMallService.createOrderItem(orderId, cartGoodsDTO);
            // 如果商品有关联商品，则将关联商品添加进订单项
            if (cartGoodsDTO.getRelateGoodsId() != null) {
                String[] relateGoodsIdList = cartGoodsDTO.getRelateGoodsId().split("/");
                System.out.println(Arrays.toString(relateGoodsIdList));
                if (relateGoodsIdList.length > 1) {
                    for (String relateGoodsId : relateGoodsIdList) {
                        exchangeMallService.createOrderItemRelate(orderId,relateGoodsId);
                    }
                }
            }
        }
        // 删除购物车中的商品
        for (CartGoodsDTO cartGoodsDTO : CartGoodsList) {
            cartServiceImpl.deleteCartByCartId(cartGoodsDTO.getCartId());
        }
        return AjaxResult.success(orderId);
    }

    /**
     * 获取订单中的商店信息
     * @param orderId 订单id
     * @return 商店地址列表
     */
    @GetMapping("/selectOrderShopAddress")
    public AjaxResult selectOrderShopAddress(@RequestParam("orderId") Long orderId) {
        return AjaxResult.success(exchangeMallService.selectOrderShop(orderId));
    }

    /**
     * 通过订单id获取订单列表
     * @param orderId 订单id
     * @return 订单列表
     */
    @GetMapping("/selectOrderListByOrderId")
    public AjaxResult selectOrderListByOrderId(@RequestParam("orderId") Long orderId) {
        return AjaxResult.success(exchangeMallService.selectOrderListByOrderId(orderId));
    }

    /**
     * 支付订单
     * @param req 请求信息
     * @return 结果
     */
    @PostMapping("/payOrder")
    public AjaxResult payOrder(@RequestBody Map<String, Object> req) {
        exchangeMallService.payOrder(req);
        return AjaxResult.success();
    }

    /**
     * 立即支付创建订单
     * @param userId 用户id
     * @param goodsId 商品id
     * @param goodsCounts 商品数量
     * @param stander 商品规格
     * @return 结果
     */
    @PostMapping("/createOrderNow")
    public AjaxResult createOrderNow(@RequestParam("userId") Long userId, @RequestParam("goodsId") Long goodsId, @RequestParam("goodsCounts") Long goodsCounts, @RequestParam("stander") String stander) {
        Long orderId = exchangeMallService.createOrderInfo(userId);
        exchangeMallService.createOrderItemNow(orderId, goodsId, goodsCounts, stander);
        return AjaxResult.success(orderId);
    }



}
